import {isProxy, reactive, nextTick} from 'vue'
import {createNamespacedHelpers, createStore} from 'vuex'
import MetaUtils from '@/utils/MetaUtils'
import {EventBus, EventType, MetaEventType, MetaRemoveEvent} from "@/event";
import {UnionType} from "@/store/consts";
import {foreignMetas} from "@/metas/ComponentMetas";
// const defaultList = {id: MetaUtils.getMetaId(), type: 'dl', union: UnionType.List, name: '默认列表'}

function initTabMetas(meta) {
    let tabMetas = meta['tabMetas'];
    meta['tabModel'] = meta['tabModel'] || {};

    Object.keys(tabMetas).forEach((key) => {
        tabMetas[key]['metas'].forEach(formMeta => {
            if(formMeta.type == 'divider') return;

            // 值不存在
            let oriValue = meta['tabModel'][formMeta.field];
            if(oriValue == null) { // 使用默认值
                let stringify = JSON.stringify(formMeta.default);
                meta['tabModel'][formMeta.field] = JSON.parse(stringify || null)
            }
            if(formMeta.realField) {
                if(formMeta.realField instanceof Array) {
                    formMeta.realField.forEach(field => {
                        meta['tabModel'][field] = null;
                    })
                } else {
                    for(let key in formMeta.realField) {
                        let value = formMeta.realField[key];
                        let s = JSON.stringify(value);
                        meta['tabModel'][key] = JSON.parse(s)
                    }
                }
            }
        })
    });

}

export default createStore({
    namespaced: true,
    state: {
        id: null, // 后台自增主键(如果值存在表示当前处于编辑状态)
        reset: false, // 重置系统
        global: {
            isGen: false, // 是否已经生成
            isEdit: false, // 是否处于编辑模式
            name: 'xx',
            current: null, // modal、drawer
        },
        paths: [],
        activeMeta: null, // 当前激活的元对象
        rightTabMetas: {},
        rightTabModel: {},
        // 编辑表单配置
        edit: {
            metas: [],
            funMetas: [],
            visible: false, // 显示
            meta: {tabModel: {}, tabMetas: {}},
        },

        // 列表页
        list: {
            metas: [],
            meta: {tabModel: {}, tabMetas: {}}
        },

        // 搜索栏配置
        search: {
            metas: [],
            funMetas: [], // 功能按钮
            meta: {tabModel: {}, tabMetas: {}}
        },

        // 表格配置
        table: {
            metas: [],
            funMetas: [], // 功能按钮
            meta: {tabModel: {}, tabMetas: {}}
        },

        // 容器配置
        container: {
            metas: [],
            funcList: [], // 功能列表
            meta: {tabModel: {}, tabMetas: {}},
        },

        // sql脚本配置
        sqlManager: {
            sqlScript: '', // sql 脚本
            sqlData: [], // sql列
            isImport: false, // 是否已经导入到数据库
            sqlVisible: false, // sql管理modal
        },

        // 数据模拟
        preview: {
            reset: true,
            status: false,
            dataSource: [],
            editVisible: false
        },

        // 已存数据
        store: {
            dictList: [], // 字典列表
            tableList: [], // 表列表
            foreignList: [], // 已添加的外键列表
        }
    },
    getters: {
        isReset: state => state.reset,
        isEdit: state => state.id != null && state.id > 0,
        preview: state => state.preview,

        editMeta: state => state.edit.meta,
        editMetas: state => state.edit.metas,
        editVisible: state => state.edit.visible,
        editFunMetas: state => state.edit.funMetas,
        editTabModel: state => state.edit.meta.tabModel,

        listMeta: state => state.list.meta,
        listMetas: state => state.list.metas,
        listTabMetas: state => state.list.meta.tabMetas,
        listTabModel: state => state.list.meta.tabModel,

        // 右侧元数据和对应的model
        tabsMetas: state => state.rightTabMetas,
        tabsModel: state => state.rightTabModel,

        tableMeta: state => state.table.meta,
        tableMetas: state => state.table.metas,
        tableFunMetas: state => state.table.funMetas,
        tableTabMetas: state => state.table.meta.tabMetas,
        tableTabModel: state => state.table.meta.tabModel,

        activeMeta: state => state.activeMeta,

        searchMeta: state => state.search.meta,
        searchMetas: state => state.search.metas,
        searchFunMetas: state => state.search.funMetas,
        searchTabModel: state => state.search.meta.tabModel,

        containerMeta: state => state.container.meta,
        containerMetas: state => state.container.metas,
        containerFuncMetas: state => state.container.funcList,

        sqlData: state => state.sqlManager.sqlData,
        sqlVisible: state => state.sqlManager.sqlVisible,
        sqlScript: state => state.sqlManager.sqlScript,

        dbStorage: state => state.store,
    },
    mutations: {
        recover(state, data) {
            state.id = data.id;
            state.edit = data.edit;
            state.search = data.search;
            state.global = data.global;
            state.table = data.formTable;
            state.container = data.container;
        },
        resetSys(state) {
            EventBus.clearEvents(); // 移除所有事件

            state.activeMeta = null;

            state.sqlManager.sqlScript = '';
            state.sqlManager.sqlVisible = false;
            state.sqlManager.sqlData.length = 0;

            state.container.meta = {tabMetas: {}, tabModel: {}};
            state.container.metas.length = 0;
            state.container.funcList.length = 0;

            state.table.metas.length = 0;
            state.table.funMetas.length = 0;
            state.table.meta = {tabMetas: {}, tabModel: {}};

            state.edit.visible = false;
            state.edit.metas.length = 0;
            state.edit.funMetas.length = 0;
            state.edit.meta = {tabMetas: {}, tabModel: {}};

            state.search.metas.length = 0;
            state.search.funMetas.length = 0;
            state.search.meta = {tabMetas: {}, tabModel: {}};
        },
        // 切换路径
        switchPathTo(state, path) {
            let paths = state.paths;

            paths.forEach(item => item.active = false);
            let oriPath = paths.filter(item =>
                item.type == path.type).find(item => true);
            if(oriPath != null) {
                Object.assign(oriPath, path);
            } else {
                path['active'] = true;
                paths.push(path);
            }

            paths.sort((a, b) => a.sort > b.sort ? 1 : a.sort == b.sort ? 0 : -1)
        },
        // 切换组件的左边元数据
        switchTabMetasTo(state, type) {
            let component = state[type];
            state.rightTabMetas = component.tabMetas;
            state.rightTabModel = component.tabModel;
        },
        switchEditVisible(state, visible) {
            state.edit.visible = visible;
        },
        // 切换当前的激活对象
        switchActiveMetaTo(state, meta) {
            meta.active = true; // 激活当前元
            if(state.activeMeta && meta != state.activeMeta) {
                state.activeMeta.active = false; // 失活老组件
            }

            state.activeMeta = meta;
            let activePane = meta['activePane'] // 打开右边默认的激活面板
            state.rightTabMetas = meta.tabMetas;
            state.rightTabModel = meta.tabModel;
            EventBus.publish(EventType.switchTab, activePane || 'basic')
        },
        // 切换编辑元类型
        switchEditMetaType(state, type) {

        },
        // 切换sql管理modal
        switchSqlVisible(state, visible) {
            state.sqlManager.sqlVisible = visible;
        },
        switchPreviewTo(state, preview) {
          state.preview.status = preview;
          if(!preview) { // 关掉只会就需要重置
              state.preview.reset = true; // 在重新查询的时候修改此状态到 false
          }
        },
        // 更新搜索元列表
        updateSearchFormMetas(state, meta) {
            let metas = state.search.metas;
            let include = MetaUtils.includeMetas(metas, meta.id);
            if(include > -1) { //已经存在的直接删除
                metas.splice(include, 1);
            } else { // 不存在则加入列表
                if(!isProxy(meta)) {
                    meta = reactive(meta);
                }
                metas.push(meta);
            }
        },
        updateTableColumnsMetas(state, meta) {
            let metas = state.table.metas;
            let index = MetaUtils.includeMetas(metas, meta.id);
            if(index > -1) {
                metas.splice(index, 1);
            } else {
                initTabMetas(meta)
                metas.splice(metas.length - 1, 0, meta);
            }
        },
        initMeta(state, meta) {
            initTabMetas(meta);
        },
        initEditMeta(state, meta) {
            state.edit.meta = meta;
            initTabMetas(state.edit.meta)
            meta['funMetas'] = meta['funMetas'] || [];
            EventBus.publish(MetaEventType.editCreate, meta)
        },
        removeEditMetas(state, meta) {
            let metas = state.edit.metas;
            let index = MetaUtils.includeMetas(metas, meta.id);
            if(index > -1) {
                metas.splice(index, 1);
                EventBus.publish(MetaRemoveEvent.delEditMeta, meta);
            }
        },
        removeTableColumnMeta(state, meta) {
            let metas = state.table.metas;
            let index = MetaUtils.includeMetas(metas, meta.id);
            if(index > -1) {
                metas.splice(index, 1);
                EventBus.publish(MetaRemoveEvent.delTableColumn, meta)
            }
        },
        removeSearchFormMeta(state, meta) {
            let metas = state.search.metas;
            let index = MetaUtils.includeMetas(metas, meta.id);
            if(index > -1) {
                metas.splice(index, 1);
                EventBus.publish(MetaRemoveEvent.delSearchFormMeta, meta);
            }
        },
        removeSearchFunMeta(state, meta) {
            let metas = state.search.funMetas;
            let index = MetaUtils.includeMetas(metas, meta.id);
            if(index > -1) {
                metas.splice(index, 1);
            }
        },
        removeEditFunMeta(state, meta) {
            let funMetas = state.edit.funMetas;
            let index = MetaUtils.includeMetas(funMetas, meta.id);
            if(index > -1) {
                funMetas.splice(index, 1);
            }
        },
        // 初始化表单元数据
        initFormTabMeta(state, meta) {
            EventBus.publish(MetaEventType.formBeforeCreate, meta);
            initTabMetas(meta);
            EventBus.publish(MetaEventType.formAfterCreate, meta);
        },
        initSearchFormTabMeta(state, meta) {
            initTabMetas(meta);
        },
        setListTabMetas(state, tabMetas) {
            state.list.meta.tabMetas = tabMetas;
            initTabMetas(state.list.meta);
            EventBus.publish(MetaEventType.list, state.list.meta)
        },
        setTableTabMetas(state, tabMetas) {
            state.table.meta.tabMetas = tabMetas;
            initTabMetas(state.table.meta);
            EventBus.publish(MetaEventType.table, state.table.meta)
        },
        setSearchTabMetas(state, searchMetas) {
            state.search.meta.tabMetas = searchMetas;
            initTabMetas(state.search.meta);
            EventBus.publish(MetaEventType.search, state.search.meta)

        },
        setContainerTabMetas(state, tabMetas) {
            state.container.meta.tabMetas = tabMetas;
            initTabMetas(state.container.meta);
            EventBus.publish(MetaEventType.container, state.container.meta)
        },
        addToTabsMetas(type, metas) {

        },
        addToFuncList(state, func) {
            state.container.funcList.push(func);
        },
        removeFunc(state, func) {
            let index = state.container.funcList.findIndex(item => item == func);
            if(index > -1) {
                state.container.funcList.splice(index, 1)
            }
        },
        addContainerMetas(state, meta) {
            state.container.metas = meta;
        },
        removeContainerMeta(state, meta) {
            let index = state.container.metas.findIndex(item => item == meta);
            if(index > -1) {
                state.container.metas.splice(index, 1);
            }
        },
        // 激活组件的样式
        activeClass(state, meta) {
            return meta['active'] ? 'ivz-item-active' : '';
        },

        setViewGlobalAttr(state, val) {
            state.global.name = val.name;
        },
        // 设置sql数据
        setSqlData(state, data) {
            state.sqlManager.sqlData = data;
        },
        // 设置sql脚本
        setSqlScript(state, script) {
            state.sqlManager.sqlScript = script;
        },
        // 设置外键
        setForeignToList(state, {table, field, id}) {
            let find = state.store.foreignList.find(item => item.id == id);
            let tableObj = state.store.tableList.find(item => item.value == table);
            // 已经存在此外键组件
            if(find) {

            } else { // 不存在
                state.store.foreignList.push({label: table, value: table, children: tableObj.children})
            }
        },
        // 设备表列表
        setTableList(state, tableList) {
            state.store.tableList = tableList;
        }
    },
    actions: {
        // 加载字典列表
        loadingDictList() {

        },

        // 加载数据库表列表
        loadingDbList({state}) {
            if(import.meta.env.PROD) {

            } else {
                state.store.tableList = [
                    {label: 't_demo', value: 't_demo', children: [
                            {label: 'id', value: 'id'},
                            {label: 'user_name', value: 'user_name'},
                            {label: 'real_name', value: 'real_name'},
                        ]
                    }
                ]
            }
        }
    }
})


